package com.smap.control;

import java.util.List;

import com.smap.core.Layer;
import com.smap.core.Marker;
import com.smap.core.XY;
import com.smap.event.MapEvent;
import com.smap.layer.InfoHandler;
import com.smap.marker.Popup;

public class InfoControl extends AbstractControl {

	@Override
	public void execute(String cmd) {

	}

	public void display(List infos, XY xy) {
		StringBuffer html = new StringBuffer();
		for (Object info : infos) {
			if (info != null) {
				html.append(info.toString());
			}
		}
		String content = (html + "").trim();
		if (content.length() > 0) {
			Marker p = Popup.get().set(xy, html + "");
			map.addMarker(p);
			p.draw();
		} else {
			Popup.get().remove();
		}
	}

	@Override
	void onEvent(MapEvent evt) {
		if ("dbclick".equals(evt.type)) {
			evt.stop();
		}
		final XY latlon = this.map.pixelToMap(new XY(evt.x, evt.y));

		InfoHandler handler = new InfoHandler() {
			public void render(List infos) {
				display(infos, latlon);
			}
		};
		if ("click".equals(evt.type)) {
			List<Layer> layers = map.getLayers();
			handler.start(layers.size());
			for (Layer layer : layers) {
				layer.getInfo(evt.x, evt.y, handler);
			}
		}
	}

	@Override
	public String[] getCmd() {
		return new String[] { "info" };
	}

	@Override
	void init() {
		this.setGroup("main");
	}

}
